package com.ltu.timkor6.gamesite.games.memory.server;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.ltu.timkor6.gamesite.shared.DoubleArray;

/**
 * Memory
 * 
 * @author tim
 *
 */
public class Memory
{
	private int memoryColumns;
	private int memoryRows;
	private int memorySize;
	
	private Random random;
	private DoubleArray memory;
	private DoubleArray matches;
	
	public Memory()
	{
	}
	
	/**
	 * Memory how to
	 *  - Choose a random image
	 *  - Put 2 images randomly on the surface
	 *  - 
	 * 
	 * 1. Create a list with positions list must be of even size.
	 *   2. Generate a random number between 0 and current list size.
	 *   3. When a location is taken, remove that item from the list.
	 *   4. This must be done twice for every "image".
	 * 5. Loop 2-4 until list is empty.
	 */
	public void generate(int rows, int columns)
	{
		this.memoryColumns = rows;
		this.memoryRows = rows;
		
		this.memorySize = rows*columns;
		
		// TODO - Add seed value?
		this.random = new Random();
		
		
		memory = new DoubleArray(rows, columns);
		matches = new DoubleArray(rows, columns);
		
		
		List<Integer> list = new ArrayList<Integer>(this.memorySize);
		for(int i = 0; i < this.memorySize; i++)
		{
			list.add(i);
		}
		
		List<Integer> numbers = new ArrayList<Integer>();
		int j = 0;
		for(int i = 0; i < this.memorySize; i++)
		{
			if(i % 2 == 0)
			{
				j++;
			}
			numbers.add(j);
		}
		
		// Big cells 3 x 3
		for(int row = 0; row < this.memoryRows; row++)
		{
			for(int column = 0; column < this.memoryColumns; column++)
			{
				// Generate a random location
				int number = getRandom(0, numbers.size());
				
				// Add the location
				memory.set(row, column, numbers.get(number));
				
				// Remove from list
				numbers.remove(number);
			}
		}
	}
	
	public int getPosition(int row, int column)
	{
		return this.memory.get(row, column);
	}
	
	public void createGame()
	{
		createGame(40);
	}
	
	/**
	 * Creates a Suduku game with 40 preset numbers.
	 */
	public void createGame(int numbers)
	{
		
	}
	
	public boolean validate()
	{
		return (this.matches.get().equals(this.memory.get()));
	}
	
	public DoubleArray getMatches()
	{
		return this.matches;
	}
	
	/**
	 * Generate a random number between lower up to upper.
	 * @param lower
	 * @param upper
	 * @return
	 */
	private int getRandom(int lower, int upper)
	{
		int numbers = random.nextInt(upper-lower);
		
		return numbers + lower;
	}
	
	public int getSize()
	{
		return this.memorySize;
	}
	
	/**
	 * Print a DubbleArray with rows and cols.
	 */
	public void print()
	{
		System.out.println("Suduku of size " + this.memory.getRowSize() + "x" + this.memory.getColSize());
		
		for(int row = 0; row < this.memory.getRowSize(); row++)
		{
			for(int col = 0; col < this.memory.getColSize(); col++)
			{
				System.out.print(this.memory.get(row, col) + " ");
			}
			
			System.out.println("");
		}
	}
}
